import Queue, requests
class FakeResponse():
    def __init__(self):
        self.content = ""
    def setNormal(self):
        self.content = ''
        self.data = "test test test test"
        self.headerList = []
        self.headerList.append('HTTP/1.1 200 OK')
        self.headerList.append('Cache-Control: public, max-age=60')
        self.headerList.append('Content-Type: text/html; charset=utf-8')
        self.headerList.append('Content-Encoding: gzip')
        self.headerList.append('Expires: Fri, 18 Apr 2014 09:40:21 GMT')
        self.headerList.append('Last-Modified: Fri, 18 Apr 2014 09:39:21 GMT')
        self.headerList.append('Vary: *')
        self.headerList.append('X-Frame-Options: SAMEORIGIN')
        self.headerList.append('Date: Fri, 18 Apr 2014 09:39:20 GMT')
        self.headerList.append('Content-Length: '+str(len(self.data)))
        self.content = "\r\n".join(self.headerList)
        self.content += "\r\n\r\n"
        self.content += self.data
        
    def checkResponse(self,response):
        for key in response.headers:
            modKey = self.headerKeyMod(key)
            line = ": ".join((modKey,response.headers[key]))
            if self.headerList.index(line) == -1:     
                return False
        if response.payload != "test test test test":
            return False
        return True

    def headerKeyMod(self,key):
        result = ""
        status = 0
        for char in key:
            if status == 0:
                result += char.upper()
                status = 1
            elif status == 1:
                result += char
                if char == "-":
                    status = 2
            elif status == 2:
                result += char.upper()
                status = 1
        return result


class FakeSession():
    def __init__(self,sid):
        self.sid = sid

    def post(self,*args,**kwargs):
        response = FakeResponse()
        if kwargs['data'] == "EmptyResponse":
            pass
        elif kwargs['data'] == "ConnectionError":
            raise requests.exceptions.ConnectionError 
        else:
            response.setNormal()
        return response
        
    

class FakeConnectionManager():
    sessions = []
    abandonSessionQueue = None
    shutDownFlag = None
    isStartUp = None
    availiableProxies = None
    googleFrontServerIp = None
    googleFrontServerStatus = None
    
    
    def __init__(self,sessionCount):
        self.isStartUp = True
        self.availiableProxies = Queue.Queue()
        self.abandonSessionQueue = Queue.Queue()
        self.shutDownFlag = False
        self.callback = None
        self._makeGoogleFrontServerList()
        self.newSessions = []
        for i in range(sessionCount):
            self.newSessions.append(FakeSession(i))
        


    def _threadInit(self):
        #find 5 just use first 5
        #self._simpleTestConnection(self.googleFrontServerIp[0:10])
        pass

    def _makeGoogleFrontServerList(self):
        pass

    def checkAbandonSesson(self):
        
        try:
            abandonSession = self.abandonSessionQueue.get(block = True,
                                                          timeout = 1)
            abandonSession.close()

            self._testOneProxy()
        except Queue.Empty:
            pass
            
    def checkAvailiableProxies(self):
        try:
            while(True):
                result,proxy = self.availiableProxies.get(block = True,
                                                          timeout = 1)
                if result == True and self.callback != None:
                    
                    session = self._setProxySession(proxy.getAddress())
                    self.callback(session)
                
        except Queue.Empty:
            pass

    def checkLog(self):
        pass
        
    def run(self):
        if self.isStartUp :
            self.isStartUp = False
            self._threadInit()
            
        while(not self.shutDownFlag):
            self.checkAbandonSesson()
            self.checkAvailiableProxies()
            self.checkLog()       
            
            
            
        self._closeSessions()
        
    def getSession(self,count = 1,block = False,timeout = None,callback = None):
        #every new sessions makes a callback
        # to do make this stronger
        sessions = []
        self.callback = callback            
        return self.newSessions

    def _testOneProxy(self):
        pass

    
    def abandonSession(self,session):
        self.abandonSessionQueue.put(session)
        

    def _setProxySession(self,proxy):
        pass
    
    def _simpleTestConnection(self,proxyList):
        pass #we should do something
        

    def shutDown(self):
        self.newSessions =[]
        self.shutDownFlag = True

    def _closeSessions(self):
        pass
    
    def getCM(self):
        return self
